package com.fili.params;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Date: Sep 8, 2005
 * Time: 6:56:03 PM
 *
 * @author Claudiu-Florin FILIMON for Borux Consulting S.R.L.
 */
public class XMLHelper
{
	public static String quoteCharacters(String s)
	{
		StringBuffer result = null;
		for (int i = 0, max = s.length(), delta = 0; i < max; i++)
		{
			char c = s.charAt(i);
			String replacement = null;

			if (c == '&')
			{
				replacement = "&amp;";
			}
			else if (c == '<')
			{
				replacement = "&lt;";
			}
			else if (c == '\r')
			{
				replacement = "&#13;";
			}
			else if (c == '\n')
			{
				replacement = "&#10;&#13;";
			}
			else if (c == '>')
			{
				replacement = "&gt;";
			}
			else if (c == '"')
			{
				replacement = "&quot;";
			}
			else if (c == '\'')
			{
				replacement = "&apos;";
			}
			else if (c > 127)
			{
				replacement = "&#" + ((int) c) + ";";
			}

			if (replacement != null)
			{
				if (result == null)
				{
					result = new StringBuffer(s);
				}
				result.replace(i + delta, i + delta + 1, replacement);
				delta += (replacement.length() - 1);
			}
		}
		if (result == null)
		{
			return s;
		}
		return result.toString();
	}

	public static void write(String s, OutputStream os) throws IOException
	{
		os.write(s.getBytes());
	}

	public static void writeElement(String leading, String category, String content, OutputStream os) throws IOException
	{
		write(leading + "<" + category + ">" + quoteCharacters(content) + "</" + category + ">\n", os);
	}
}
